package com.example.javaee_library.Controller;/**
 * @author Miao-yongzheng
 * @create 2021-12-14 21:07
 */

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.StatefulException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.system.UserInfo;


import com.alibaba.fastjson.JSONObject;
import com.example.javaee_library.Entity.Appointment;
import com.example.javaee_library.Entity.Book;
import com.example.javaee_library.Entity.User;
import com.example.javaee_library.Entity.action;
import com.example.javaee_library.Service.Book_Service;
import com.example.javaee_library.Service.User_Service;
import com.example.javaee_library.dao.UserDao;
import com.example.javaee_library.dto.JsonData;
import com.example.javaee_library.exception.NoNumberException;
import com.mysql.cj.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.NotFoundException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: 34911
 * @time: 2021/12/14 21:07
 */
@Controller
@Slf4j
@RequestMapping("Customer")
public class CustomController {
    @Autowired
    User_Service user_servicel;
    @Autowired
    Book_Service book_service;
    @Autowired
    UserDao userDao;


    @RequestMapping("/403")
    public String unauth(){
        return "403";
    }

    @GetMapping("/Userdownloadexcel.do")
    public void getUser_Excel(HttpServletResponse response,HttpServletRequest request) {
        List<User> list = (List<User>) request.getSession().getAttribute("list");
        System.out.println(list.size());
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义标题别名
        writer.addHeaderAlias("Id", "学号");
        writer.addHeaderAlias("password", "年龄");
        writer.addHeaderAlias("authority", "生日");
        writer.addHeaderAlias("email", "email");
        // 合并单元格后的标题行，使用默认标题样式
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        String name = "User";
        response.setHeader("Content-Disposition","attachment;filename="+name+".xls");
        ServletOutputStream out= null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            // 关闭writer，释放内存
            writer.close();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);

    }
    @RequestMapping("/actiondownloadexcel.do")
    public void getaction_Excel(HttpServletResponse response,HttpServletRequest request) throws IllegalAccessException, IOException,
            InstantiationException {
        List<action> list = (List<action>) request.getSession().getAttribute("list");
        System.out.println(list.size());
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义标题别名
        writer.addHeaderAlias("id", "操作id");
        writer.addHeaderAlias("book_id", "book_id");
        writer.addHeaderAlias("student_id", "学号");
        writer.addHeaderAlias("operation", "操作");
        writer.addHeaderAlias("appoint_Time", "时间");
        // 合并单元格后的标题行，使用默认标题样式
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        String name = "action";
        response.setHeader("Content-Disposition","attachment;filename="+name+".xls");
        ServletOutputStream out= null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            // 关闭writer，释放内存
            writer.close();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
    @RequestMapping("/Bookdownloadexcel.do")
    public void getBook_Excel(HttpServletResponse response,HttpServletRequest request) throws IllegalAccessException, IOException,
            InstantiationException {
        List<Book> list = (List<Book>) request.getSession().getAttribute("list");
        System.out.println(list.size()+"fuck");
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义标题别名
        writer.addHeaderAlias("book_id", "book_id");
        writer.addHeaderAlias("name", "图书名");
        writer.addHeaderAlias("number", "数量");
        // 合并单元格后的标题行，使用默认标题样式
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        String name = "book";
        response.setHeader("Content-Disposition","attachment;filename="+name+".xls");
        ServletOutputStream out= null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            // 关闭writer，释放内存
            writer.close();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

/*    @GetMapping("/signOut")
    public ModelAndView SignOut()
    {

    }*/

    /*/**
    * @Description: 获取验证码
    * @Param: [response]
    * @return: [response]
    * @Author: Miao
    * @Date: 2022/1/5
    */
    LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30);
@RequestMapping("/getCode")
public void getCode(HttpServletResponse response) {
    // 随机生成 4 位验证码
    RandomGenerator randomGenerator = new RandomGenerator("0123456789abcdefg", 4);
    // 定义图片的显示大小
    lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30);
    response.setContentType("image/jpeg");
    response.setHeader("Pragma", "No-cache");
    try {
        // 调用父类的 setGenerator() 方法，设置验证码的类型
        lineCaptcha.setGenerator(randomGenerator);
        // 输出到页面
        lineCaptcha.write(response.getOutputStream());
        // 打印日志
        log.info("生成的验证码:{}", lineCaptcha.getCode());
       /* lineCaptcha.verify();验证*/
        // 关闭流
        response.getOutputStream().close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

    @GetMapping("/login")
    public ModelAndView login(@RequestParam("Username")String Username,
                              @RequestParam("Password")String Password,
                              ModelAndView modelAndView,
                              HttpServletRequest request,
                              HttpServletResponse response,
                              @RequestParam("code") String code)
    {
        System.out.println(Username+"验证码是"+code);
        if( !lineCaptcha.verify(code))
        {
            modelAndView.addObject("msg","验证码错误");
            modelAndView.setViewName("/index");
            return modelAndView;
        }

        Subject subject = SecurityUtils.getSubject();//shiro整合
         String md5Str = SecureUtil.md5(Password);
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                Username,
                md5Str);

       /* LOGGER.info("secureUtil md5:{}", md5Str);*/
            User user = user_servicel.Login(Username,md5Str);
            if(user==null||user.getDeleted()==1)
            {
                modelAndView.addObject("msg","用户名不存在或被删除");
                modelAndView.setViewName("/index");
                return modelAndView;
            }
            if(user.getState()==1)
            {
                modelAndView.addObject("msg","账号被冻结");
                modelAndView.setViewName("/index");
                return modelAndView;
            }
            System.out.println(user.toString()+"啊啊啊啊啊");
            request.getSession().setAttribute("userName",user.getId());
            request.getSession().setAttribute("user",user);
            System.out.println(user.getId());
            modelAndView.addObject("list",book_service.Serach(""));
            modelAndView.setViewName("listbook");
            //modelAndView.setViewName("index");
        /*try {
            subject.login(usernamePasswordToken);
            return modelAndView;
        }*/
        subject.login(usernamePasswordToken);
        return modelAndView;
       /* catch (UnknownAccountException e) {
            //用户名不存在
            modelAndView.addObject("msg","用户名不存在");
            modelAndView.setViewName("");
            return modelAndView;
        }catch (IncorrectCredentialsException e) {
            //密码错误
            modelAndView.addObject("msg","密码错误");
            modelAndView.setViewName("");
            return modelAndView;
        }
*/
    }


    @GetMapping(value = "/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView){
        HttpSession session=request.getSession();
        session.invalidate();
        modelAndView.setViewName("index");
        return "index";
    }



    @RequestMapping(value = "/listbook", method = RequestMethod.GET)
    private ModelAndView list(ModelAndView model,@RequestParam("bookName")String bookName,
                              HttpServletRequest request,
                              HttpServletResponse response) {
        List<Book> list = book_service.Serach(bookName);
        request.getSession().setAttribute("list",list);
        System.out.println(list.get(0));
        model.addObject("list",list);
        model.setViewName("listbook");
        // list.jsp + model = ModelAndView
        return model;// WEB-INF/jsp/"list".jsp
    }

    @GetMapping("/myAppoint")
    public ModelAndView myAppoint(ModelAndView modelAndView ,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
    {
        User user = (User) request.getSession().getAttribute("user");
        String UserId = String.valueOf(user.getId());

        List<Appointment> appointmentList = user_servicel.myAppoint(UserId);
        System.out.println(appointmentList.size());
        request.getSession().setAttribute("list",appointmentList);
        modelAndView.addObject("list",appointmentList);
        modelAndView.setViewName("myAppoint");
        return  modelAndView;
    }

    @GetMapping("/returnBook")
    public JsonData returnBook(@RequestParam("book_id") String book_id,HttpServletRequest request, HttpServletResponse response)
    {
        User User = (User) request.getSession().getAttribute("user");
        String UserId = String.valueOf(User.getId());
        if(book_service.returnBook(Convert.toInt(book_id),Convert.toInt(UserId)))
            return JsonData.buildSuccess("还书成功");
        else
            return JsonData.buildError("还书失败");

    }

    @ResponseBody
    @GetMapping("/timeout")
    public JSONObject timeout(HttpSession session) throws Exception {

        JSONObject obj = new JSONObject();

        String userCode = (String) session.getAttribute("user");

        obj.put("data", userCode);

        obj.put("code", 0);

        obj.put("message", "长时间未操作，身份已过期，请重新登录！");

        return obj;
    }



}
